Dictionaries

A Python dictionary is just like those giant fat books that you don't use anymore: there is a key (the "word" you want to look up) associated with a value (the corresponding "definition" of the word or key). This key–value pair is what makes a dictionary a unique container.

Properties of dictionaries:

Keys

  • Immutable
    • cannot change an existing key
  • unique
    • cannot have multiple identical keys corresponding to different values
  • not stored an any particular order
    • object access can only be by numeric index if that number is, in fact, a defined key

Values

  • can be any object without restriction
    • values do not have to be unique or immutable

In [ ]:
# start with an empty dictionary, notice dictionaries are enclosed in squiggly brackets
derp = {}

key = "daniel chen"
value = 25

# you fill dictionaries, just like lists

derp = {key:value, "niels bantilan": 25}
print derp

# note dictionaries are not ordered, DO NOT assume any order when working with dictionaries

So we have an initial dictionary with key:value pairs, how do we extend it to and add more key:values?


In [ ]:
# derp["my_new_key"] = "my_new_value"
print derp

In [ ]:
derp["Vivian Peng"] = 25
print derp

In [ ]:
# remove entry from dictionary
derp['greg wilson'] = 85
print derp

del derp['greg wilson']
print derp

In [ ]:
# assigning a new value to a key that already exists will overwrite the original value
derp["daniel chen"] = 21
print derp

The main thing we are interested in, however, is using a dictionary. How do we 'look' keys up? Just like list indexing, as it turns out.


In [ ]:
# How old is Daniel Chen?
print derp["daniel chen"]

In [ ]:
# Alernatively:
print derp.get("daniel chen")

Let's look for a key that does not exist in this dictionary:


In [ ]:
print derp["monty python"]

In [ ]:
# Note the different result here, so you will handle missing keys differently.
print derp.get("monty python")

The 'in' operator is an easy way to check for a key.


In [ ]:
'monty python' in derp

In [ ]:
'daniel chen' in derp

You can also use the 'has_key' method


In [ ]:
derp.has_key('monty python')

In [ ]:
derp.has_key('daniel chen')

More dictionary stuff


In [ ]:
# List all keys.
print derp.keys()

In [ ]:
# List all values.
print derp.values()

In [ ]:
# Length = (number of key:value pairs)
print len(derp)

In [ ]:
# if you get confused about variable type, then
type(derp) # is your best friend!

Exercise

1

Load a dictionary with the following key–value pairs. Print it.

key value
fname your first name
lname your last name
age 25
height 69
weight 180

In [ ]:
# This is one approach, where you directly fill the dictionary
my_dict = {}

my_dict = {"fname":"daniel", "lname":"chen", "age":25, "height":69, "weight":180}

print my_dict

In [ ]:
# This is another approach whre you dill the dictionary using variables

fname = "daniel"
lname = "chen"
age = 25
height = 69
weight = 180
my_dict = {'fname':fname, 'lname':lname, 'age':age, 'height':height, 'weight':weight}

print my_dict

2

A more advanced question: how would you store the above data in a single dictionary entry?

(You could accomplish this using a list of the above values, but a more straightforward solution is like a database: simply store the dictionary above with an appropriate key, such as a number or name.)


In [ ]:
#using list
hardQuestion = {1: ["daniel", "chen", 25, 69]}
print hardQuestion

print hardQuestion.get(1)[0]

# using dictionary
hardQuestion = {1: {"fname":"daniel", "lname":"chen", "age":25, "height":69}}
print hardQuestion

print hardQuestion.get(1).get("fname")

firstPerson =  hardQuestion.get(1)
firstPerson
type(firstPerson)

print firstPerson.get("fname")

In [ ]: